#include "GLUT.h"

namespace GeorgeLib
{

// Initialise all our static pointers to NULL first before we do anything
_GLUT	*	_GLUT::GLUT_Instance	= NULL;

_GLUT::_GLUT(void)
{
}

_GLUT::~_GLUT(void)
{
	// Delete the Instance
	if(GLUT_Instance != NULL)
	{
		delete GLUT_Instance;
		GLUT_Instance = NULL;
	}
}

_GLUT* _GLUT::getInstance(void)
{
	if(GLUT_Instance == NULL)
		GLUT_Instance = new _GLUT();

	return GLUT_Instance;
}

void _GLUT::InitWindow(int * pargc, char ** argv, const char * title, GLuint displayMode, int x, int y, int width, int height)
{
	glutInit(pargc, argv);

	if(displayMode > -1)
		glutInitDisplayMode(displayMode);

	if(x > -1 && y > -1)
		glutInitWindowPosition(x, y);

	if(width > 0 && height > 0)
		glutInitWindowSize(width, height);

	glutCreateWindow(title);
}

bool _GLUT::InitWindowFromFile(int * pargc, char ** argv, char * filename)
{
	// Load file
	if(!LuaScript->LoadFile(filename))
	{		
		Logger->AddLog("Couldn't load GLUT from file");
		return false;
	}

	// Initiate and retreive the variables from the file
	char*	title				= LuaScript->getVariables("title");
	string	displayModeString	= LuaScript->getVariables("displayMode");
	int		x					= LuaScript->getVariablei("x");
	int		y					= LuaScript->getVariablei("y");
	int		width				= LuaScript->getVariablei("width");
	int		height				= LuaScript->getVariablei("height");

	// Process the variables
	GLuint displayMode = GLUT_RGBA;
	if(displayModeString.find("GLUT_INDEX") != string::npos)		displayMode |= GLUT_INDEX;
	if(displayModeString.find("GLUT_DOUBLE") != string::npos)		displayMode |= GLUT_DOUBLE;
	if(displayModeString.find("GLUT_ACCUM") != string::npos)		displayMode |= GLUT_ACCUM;
	if(displayModeString.find("GLUT_ALPHA") != string::npos)		displayMode |= GLUT_ALPHA;
	if(displayModeString.find("GLUT_DEPTH") != string::npos)		displayMode |= GLUT_DEPTH;
	if(displayModeString.find("GLUT_STENCIL") != string::npos)		displayMode |= GLUT_STENCIL;
	if(displayModeString.find("GLUT_MULTISAMPLE") != string::npos)	displayMode |= GLUT_MULTISAMPLE;
	if(displayModeString.find("GLUT_STEREO") != string::npos)		displayMode |= GLUT_STEREO;
	if(displayModeString.find("GLUT_LUMINANCE") != string::npos)	displayMode |= GLUT_LUMINANCE;

	// Pass the variables into GLUT
	InitWindow(pargc, argv, title, displayMode, x, y ,width, height);

	// If there's no errors, then return true
	LuaScript->NewState();

	return true;
}

} // namespace GeorgeLib